package com.youngjun.common.util;

import java.net.*;
import java.util.Enumeration;
import java.util.logging.Logger;


public class IPUtils {

    private static final Logger logger = Logger.getLogger(IPUtils.class.getName());

    public static String getIp() {
        String NETWORK_CARD = "eth0";
        String NETWORK_CARD_BAND = "bond0";
        String NETWORK_CARD_MAC = "en0";
        InetAddress inetAddress = null;
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {

                NetworkInterface networkInterface = networkInterfaces.nextElement();
                //单网卡或者绑定双网卡
                if ((NETWORK_CARD.equals(networkInterface.getName()))
                        || (NETWORK_CARD_BAND.equals(networkInterface.getName()))
                        || (NETWORK_CARD_MAC.equals(networkInterface.getName()))
                ) {
                    Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                    while (inetAddresses.hasMoreElements()) {
                        inetAddress = inetAddresses.nextElement();
                        if (inetAddress instanceof Inet6Address) {
                            continue;
                        }
                        return inetAddress.getHostAddress();
                    }
                    break;
                } else {
                    continue;
                }
            }
        } catch (SocketException ignored) {

        }
        throw new RuntimeException("获取IP失败!");
    }

    public static String longToIpV4(long longIp) {
        int octet3 = (int) ((longIp >> 24) % 256);
        int octet2 = (int) ((longIp >> 16) % 256);
        int octet1 = (int) ((longIp >> 8) % 256);
        int octet0 = (int) ((longIp) % 256);
        return octet3 + "." + octet2 + "." + octet1 + "." + octet0;
    }

    public static long ipV4ToLong(String ip) {
        String[] octets = ip.split("\\.");
        return (Long.parseLong(octets[0]) << 24) + (Long.parseLong(octets[1]) << 16)
                + (Long.parseLong(octets[2]) << 8) + Long.parseLong(octets[3]);
    }
}
